#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os

############################################################################

src_path = r'/rootfs/media/kasim/DataSet/Record2'
dst_path = r'/rootfs/media/kasim/DataSet/Record2/detect'

search_sub_dir = True
# search_sub_dir = False
copy_ext_file_names = {
    '.dat',
}

try:
    src_dirs = []

    src_path = os.path.normpath(src_path)
    for dir_name, sub_dirs, files in os.walk(src_path):
        dir_name = os.path.normpath(dir_name)
        if not search_sub_dir:
            if src_path != dir_name:
                # print(file_path, dir_name)
                continue
        for file_name in files:
            file_ext = os.path.splitext(file_name)[1].lower()
            if copy_ext_file_names is not None:
                if file_ext not in copy_ext_file_names:
                    continue
            src_dirs.append(os.path.join(dir_name, file_name))

    src_dirs.sort()

    if not os.path.exists(dst_path):
        os.makedirs(dst_path)

    for src_dir in src_dirs:
        src_file_path = src_dir
        base_name = src_dir.replace(os.path.normpath(src_path), '.')

        dst_file_path = os.path.normpath(os.path.join(dst_path, base_name))
        dir_dir_path = os.path.dirname(dst_file_path)
        if not os.path.exists(dir_dir_path):
            os.makedirs(dir_dir_path)
        try:
            os.system('mv \"{}\" \"{}\" -f'.format(src_file_path, dst_file_path))
        except Exception as e:
            print(e)
    os.system('chmod a+wr {} -Rf'.format(dst_path))

except Exception as e:
    print(e)

print('Finish!')

